461. 汉明距离

461. 汉明距离

Similar Question

Solution Tips

方案一: 模拟

var hammingDistance = function(x, y) {
    // 将两个数转换为二进制, 然后进行逐位对比
    const a = x.toString(2);
    const b = y.toString(2);

    let i = a.length - 1;
    let j = b.length - 1;

    let res = 0;
    while (i >= 0 || j >= 0) {
        const bitA = a[i] || '0';
        const bitB = b[j] || '0';

        if (bitA !== bitB) {
            res++;
        }

        i--;
        j--;
    }

    return res;
};
console.log(hammingDistance(1, 4))

方案二: 位运算

var hammingDistance = function(x, y) {
    let s = x ^ y, ret = 0;
    while (s != 0) {
        ret += s & 1;
        s >>= 1;
    }
    return ret;
};